package com.pj.common.base.topbar

import android.os.Bundle
import android.view.View
import androidx.annotation.StringRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.pj.common.R
import com.pj.common.annotation.LayoutParam
import com.pj.common.base.BaseFragment
import com.pj.common.base.BaseViewModel
import com.pj.common.databinding.ContainBaseTopbarBinding
import com.pj.common.utils.CommonUtils
import com.pj.common.utils.TopBarUtils


open class BaseTopBarFragment<VM : BaseViewModel, T : ViewDataBinding> :
    BaseFragment<VM, ContainBaseTopbarBinding>() {
    override fun getLayoutRes(): Int = R.layout.contain_base_topbar
    protected lateinit var mCBinding: T
    open fun getContentLayout(): Int? = null
    open fun hasBackIcon(): Boolean = false
    override fun initData(view: View, savedInstanceState: Bundle?) {
        var contentId = getContentLayout()
        var hasBack = hasBackIcon()
        if (contentId == null) {
            var layoutParam: LayoutParam = CommonUtils.findAnnotation(javaClass)
                ?: throw IllegalArgumentException("BaseToolBarActivity must has a content layout,and the param layout must not null!")
            contentId = layoutParam.layout
            hasBack = layoutParam.hasBack
            if (layoutParam.title > 0)
                mBinding.topBar.setTitle(layoutParam.title)
        }
        mCBinding = DataBindingUtil.inflate(
            layoutInflater, contentId,
            mBinding.container, false
        )
        TopBarUtils.initTopBar(mBinding.topBar, hasBack) { requireActivity().onBackPressed() }
        mBinding.container.addView(mCBinding.root)
    }

    /**
     * 手动设置topbar标题,
     * @param title 默认为空,需要传入resId,不然显示默认值(提示)
     * @param resId StringRes
     */
    fun setTopbarTitle(title: String = "", @StringRes resId: Int = R.string.app_name) {
        mBinding.topBar.setTitle(title.ifEmpty { getString(resId) })
    }
}